
import { Schema } from "express-validator";
import { getPosts, createOrEditPost, deletePost } from "../services/posts";
import validate from "@src/util/validate";
import { Request, Response, NextFunction } from "express";
import { InferSelectModel, InferInsertModel } from "drizzle-orm";
import posts from "@src/db/schema/posts";
import { addComment } from "@src/services/comments";
import debug from "debug";
import { getCategories } from "@src/services/categories";

const log = debug('app:posts-controller');

// 查询时返回的数据类型（包含所有字段）
export type PostType = InferSelectModel<typeof posts>;

// 插入/更新时的数据类型（不包含自动生成的字段）
export type NewPost = InferInsertModel<typeof posts>;

/* ------------------------------- Validators ------------------------------- */
const postSchema: Schema = {
  title: {
    isString: true,
    isLength: {
      options: { min: 3, max: 20 },
    },
    notEmpty: true,
    trim: true,
    errorMessage: 'title 必须是字符串，长度在3-20个字符之间'
  },
  content: {
    isString: true,
    notEmpty: true,
    trim: true,
    errorMessage: 'content 必须是字符串'
  },
}


/* -------------------------------- Function -------------------------------- */

/**
 *
 * @description get all posts
 * @returns
 */
export async function getAllPosts(req: Request, res: Response, next: NextFunction) {
  try {
    const result = await getPosts();
    log('获取所有文章成功', { count: Array.isArray(result) ? result.length : 0 });
    return res.status(200).json({
      success: true,
      message: '获取文章列表成功',
      data: result
    });
  } catch (err) {
    log('获取所有文章失败', err);
    next(err);
  }
}

/**
 * @description get post by id
 * @param id post id
 * @returns
 */
export async function getPostById(req: Request, res: Response, next: NextFunction) {
  try {
    const { id } = req.body;

    const result = await getPosts({ id });
    log('获取文章详情成功', { id });
    return res.status(200).json({
      success: true,
      message: '获取文章详情成功',
      data: result
    });
  } catch (err) {
    log('获取文章详情失败', { id: req.body.id, error: err });
    next(err);
  }
}

/**
 * @description create update post
 * @returns id
 */
export async function updateOrCreatePost(req: Request, res: Response, next: NextFunction) {
  console.log(req.method, req.originalUrl);
  try {
    log('文件信息', req.file); // 文件信息

    const { title, content, category, id } = req.body;

    const categories = await getCategories();

    const errors = await validate(req, res, postSchema);
    if (errors) {
      return res.render('addpost', {
        title: "Add Post",
        errors,
        categories,
      })
    }

    // 处理上传的缩略图
    let thumbimage = undefined;
    if (req.file) {
      // 构建完整的URL：协议 + 域名 + 路径
      const protocol = req.protocol; // http 或 https
      const host = req.get('host'); // 域名和端口，如 localhost:3000
      thumbimage = `${protocol}://${host}/images/uploads/${req.file.filename}`;
    }

    const result = await createOrEditPost({
      id,
      title,
      content,
      categoryId: category,
      ownerId: req.user?.id || -1,
      thumbimage: thumbimage || ''
    });

    // 成功提示
    const action = id ? '更新' : '创建';
    req.flash('success', `${action}文章成功`);
    req.session.save(err => {
      if (err) {
        console.error('Session 保存失败', err);
      }
      res.redirect(id ? `/` : '/posts/add'); // 确保 session 写入完成再重定向
    });

    // res.redirect(302, '/posts/add');

    // return res.status(200).json({
    //   success: true,
    //   message: `${action}文章成功`,
    //   data: result
    // });


  } catch (err) {
    next(err);
  }
}

/**
 *
 * @param params post id
 * @returns
 */
export async function deleteOnePost(req: Request, res: Response, next: NextFunction) {
  try {
    const { id } = req.params;

    const result = await deletePost({ id: Number(id) });

    req.flash('success', '删除文章成功');
    req.session.save(err => {
      if (err) {
        console.error('Session 保存失败', err);
      }
      res.redirect('/');
    });
    // return res.status(200).json({
    //   success: true,
    //   message: '删除文章成功',
    //   data: result
    // });
  } catch (err) {
    log('删除文章失败', { id: req.body.id, error: err });
    next(err);
  }

}


export async function createComment(req: Request, res: Response, next: NextFunction) {

  try {
    const { postId, text, ownerId } = req.body;
    const result = await addComment({ postId, text, ownerId });

    res.redirect('/posts/show/' + postId);
    // return res.status(200).json({
    //   success: true,
    //   message: '评论发布成功',
    //   data: result
    // });
  } catch (error) {
    next(error);
  }

}
